<template>
  <div class="leftDrawer-root">
    <lark-drawer border title="基地列表" title-height="40px" width="420px">
      <div class="leftDrawer-body">
        <div class="operation-root">
          <div class="input-search">
            <el-input v-model="searchParams.name" size="mini" placeholder="输入名称进行搜索" @keyup.enter.native="searchBtn">
              <el-button @click="searchBtn" slot="append" size="mini" icon="el-icon-search"></el-button>
            </el-input>
          </div>
          <div class="add-btn">
            <el-button size="mini" round icon="el-icon-plus" @click="addBtn">新增</el-button>
          </div>
        </div>


        <div class="leftDrawer-list" id="leftDrawer-list">

          <line-table @rowClick="rowClick" :table-data="dataList" :table-header="tableHeaders">
            <template v-slot:operation="{row}">
              <div style="width: 100%;text-align: center">
                <el-dropdown trigger="click">
                  <div class="ctlTask-list-row-operation-btn" style="width:15px;margin-left: 10px">
                    <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                  </div>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-edit" @click.native="updateBtn(row)">修改</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-delete" @click.native="deleteBtn(row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </line-table>
        </div>
        <div class="leftDrawer-pagination">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="pageInfo.total"
            :current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            @current-change="pageChange"
          >
          </el-pagination>
        </div>
      </div>

    </lark-drawer>


    <lark-card border :x="300" :y="100" body-height="600px" :body-width="'500px'" v-if="editDataVisible" :hidden="!editDataVisible"
               @closeAction="editDataVisible = !editDataVisible"
               card-title="基地信息" draggable
               :radius="false">
      <div class="edit-jidi">
        <div class="edit-jidi-form">
          <el-scrollbar>
            <div class="edit-jidi-container">
              <el-form ref="edit-jidi-form" :model="editDataForm" label-width="80px" :rules="rules">
                <el-form-item label="区域">
                  {{`${editDataForm.area}亩`}}
                  <el-button round size="mini" @click="selectArea">选择区域</el-button>
                </el-form-item>
                <el-form-item label="基地名称">
                  <el-input v-model="editDataForm.name" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="基地定位">
                  <el-input v-model="editDataForm.location" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="合作模式">
                  <el-input v-model="editDataForm.cooperation" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="基础设施">
                  <el-input v-model="editDataForm.basics" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="水土信息">
                  <el-input v-model="editDataForm.soilWater" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input type="textarea" v-model="editDataForm.fieldDesc" size="mini"></el-input>
                </el-form-item>

              </el-form>
            </div>
          </el-scrollbar>
        </div>
        <div class="edit-jidi-footer">
          <el-button :loading="submitBtnLoading" @click="submit" round>确定</el-button>
        </div>
      </div>

    </lark-card>


  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed } from '@vue/composition-api'
  import loading from '@/utils/loading'
  import { insertBase, deleteBase, updateBase, selectBase } from '@/api/industry/cpf'
  import lineTable from '@/components/ServiceComponents/lineTable'
  import { Message, MessageBox } from 'element-ui'
  import {
    planarArea,
    clearDrawGeometry,
    draw,
    highlightByGeometryList,
    removeHighlight,
    getGeometryListByQueryResult,
    queryResultsByUrls,
    queryByGeometry
  } from 'lark-map'

  export default {
    name: 'leftDrawer',
    props: {
      mapView: {
        type: Object,
        default: () => {
          return null
        }
      }
    },
    components: {
      lineTable
    },
    setup(props, content) {
      const tableHeaders = [
        { name: '基地名称', prop: 'name', width: '120px' },
        { name: '定位', prop: 'location', width: '100px' },
        { name: '品种数量', prop: 'partNames', width: '100px' },
        { name: '操作', prop: 'operation', type: 'slot' }
      ]
      let data = reactive({
        submitBtnLoading: false,
        rules: {},
        editDataForm: {
          id: null,
          name: null,//基地名称
          location: null,//基地定位
          cooperation: null,//合作模式
          basics: null,//基础设施
          fieldDesc: null,//描述
          soilWater: null,//水土信息，
          area: 0,//面积
          rings: null,//面
          x: null,
          y: null
        },
        editDataVisible: false,
        tableHeaders,
        dataList: [],
        pageInfo: {
          total: 0,
          pageNum: 1,
          pageSize: 7
        },
        searchParams: {
          name: ''
        }
      })
      watch(() => data.editDataVisible, (newVal) => {
        if (!newVal) {
          clearDrawGeometry({ view: props.mapView })
        }
      })
      const pageChange = async(currentPage) => {
        data.pageInfo.pageNum = currentPage
        await loadListData()
      }

      const resetFormData = () => {
        data.editDataForm = {
          id: null,
          name: null,//基地名称
          location: null,//基地定位
          cooperation: null,//合作模式
          basics: null,//基础设施
          fieldDesc: null,//描述
          soilWater: null,//水土信息，
          area: 0,//面积
          rings: null,//面
          x: null,
          y: null
        }
      }

      const loadListData = async() => {
        let load = loading(document.getElementById('leftDrawer-list'))
        try {
          let response = await selectBase({ ...data.searchParams, ...data.pageInfo })
          removeHighlight(props.mapView)
          data.dataList = response.rows
          data.pageInfo.total = response.total
        } finally {
          load.close()
        }
      }

      const addBtn = () => {
        resetFormData()
        data.editDataVisible = true
      }

      const searchBtn = async() => {
        data.pageInfo.pageNum = 1
        await loadListData()
      }
      const deleteBtn = async(item) => {
        let load = loading(document.getElementById('leftDrawer-list'))
        try {
          let response = await deleteBase(item.id)
          Message.success('删除成功')
        } finally {
          load.close()
        }
      }
      const updateBtn = (item) => {
        resetFormData()
        let { id, name, location, cooperation, basics, fieldDesc, soilWater, area, rings, x, y } = item
        data.editDataForm = {
          id: id,
          name: name,//基地名称
          location: location,//基地定位
          cooperation: cooperation,//合作模式
          basics: basics,//基础设施
          fieldDesc: fieldDesc,//描述
          soilWater: soilWater,//水土信息，
          area: area,//面积
          rings: rings,//面
          x: x,
          y: y
        }
        data.editDataVisible = true
      }

      const rowClick = async(item) => {
        content.emit('rowClick', item)
        let requestParams = {
          view: props.mapView,
          idList: ['SeedFarmService'],
          outFields: [{ parentId: 'SeedFarmService', value: ['*'] }],
          where: [{ parentId: 'SeedFarmService', value: `1=1 and id = '${item.id}'` }],
          returnGeometry: [{ parentId: 'SeedFarmService', value: true }],
          subLayerIds: [{ parentId: 'SeedFarmService', value: [0] }]
        }
        let res = await queryResultsByUrls(requestParams)
        let geometryList = getGeometryListByQueryResult({ res, merge: true })
        if (!geometryList?.length) {
          removeHighlight(props.mapView)
          return
        }
        highlightByGeometryList({ view: props.mapView, geometryList: geometryList, zoom: true })
      }

      const submit = async() => {
        //提交表单
        try {
          content.refs['edit-jidi-form'].validate(async valid => {
            if (valid) {

              if (data.editDataForm.id == null) {
                if (data.editDataForm.rings.length == 0 || data.editDataForm.x == null || data.editDataForm.y == null) {
                  console.log(data.editDataForm)
                  Message.error(`区域不能为空`)
                  return
                }
                data.submitBtnLoading = true
                await insertBase({ ...data.editDataForm, ...data.pageInfo })
              } else {
                data.submitBtnLoading = true
                await updateBase({ ...data.editDataForm, ...data.pageInfo })
              }
              loadListData()
              props.mapView.map.findLayerById('SeedFarmService').refresh()
              Message.success('操作成功')
              data.editDataVisible = false
            }
          })

        } finally {
          data.submitBtnLoading = false
        }
      }

      const queryArea = () => {
        queryByGeometry({
          view,
          geometry: currentGraphic.geometry,
          idList: ['GermplasmResourceService'],
          returnFieldName: [{ parentId: 'GermplasmResourceService', value: false }],
          returnGeometry: [{ parentId: 'GermplasmResourceService', value: true }],
          layerOption: [{ parentId: 'GermplasmResourceService', value: 'all' }],
          tolerance: [{ parentId: 'GermplasmResourceService', value: 0 }],
          subLayerIds: [{ parentId: 'GermplasmResourceService', value: [0] }]
        })
      }

      const selectArea = async() => {
        let graphic = await draw({ type: 'polygon', view: props.mapView })

        data.editDataForm.rings = JSON.stringify(graphic.geometry.rings[0])
        let area = planarArea({ geometry: graphic.geometry })
        data.editDataForm.area = (area * 10000 * 1500).toFixed(2)
        let { x, y } = graphic.geometry.extent.center
        data.editDataForm.x = x
        data.editDataForm.y = y
      }

      onMounted(() => {
        loadListData()
      })

      return { ...toRefs(data), pageChange, searchBtn, deleteBtn, updateBtn, rowClick, addBtn, selectArea, submit, resetFormData }
    }
  }
</script>

<style scoped lang="scss">
  $list-row-height: 36px;
  .leftDrawer-root {
    .leftDrawer-body {
      padding: 5px 10px 10px 10px;
      height: 42vh;

      .operation-root {
        padding: 0px 10px;
        height: 50px;
        line-height: 50px;
        display: flex;
        flex-direction: row;
        border-bottom: 1px dashed green;

        .add-btn {
          padding: 0 10px;
        }

        .input-search {
          flex: 1 0;
        }
      }

      .leftDrawer-pagination {
        height: 35px;
      }

      .leftDrawer-list {
        height: calc(42vh - 68px - 35px);
        overflow: hidden;

      }
    }

  }
</style>
<style lang="scss">
  .edit-jidi {
    padding: 10px 5px;

    .edit-jidi-form {
      .edit-jidi-container {
        padding: 0px 10px;
      }

      height: calc(598px - 20px - 40px);
      padding-bottom: 10px;
    }

    .edit-jidi-footer {
      height: 40px;
      text-align: right;
      margin-right: 10px;
      margin-top: 10px;
    }
  }
</style>
